package com.tn.po.server;



import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.IOUtils;
import org.apache.commons.vfs.FileObject;

import com.newatlanta.commons.vfs.provider.gae.GaeVFS;
import com.tn.bo.Attachment;
import com.tn.dao.AttachmentDAO;


public class AttachmentServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int rootPathLen;

	@Override
	public void init() throws ServletException {
		String rootPath = getServletContext().getRealPath("/");
		rootPathLen = rootPath.length();
		// for development on Windows
		if (System.getProperty("os.name").startsWith("Windows")) {
			rootPathLen++;
		}
		GaeVFS.setRootPath(rootPath);
	}

	@Override
	public void destroy() {
		GaeVFS.close();
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		// Check that we have a file upload request
		if (!ServletFileUpload.isMultipartContent(req)) {
			res.sendError(HttpServletResponse.SC_BAD_REQUEST,
					"form enctype not multipart/form-data");
		}
		long productId = 0;
		try {
			String path = "/gaevfs";
			
			ServletFileUpload upload = new ServletFileUpload();
			
			FileItemIterator iterator = upload.getItemIterator(req);
			String poNumber = "";
				

			while (iterator.hasNext()) {

					FileItemStream item = iterator.next();
					if (item.getFieldName().equalsIgnoreCase("attachmentId")) {
						
						poNumber = Streams.asString(item.openStream());
						System.out.println(">>>>>>>>>>>>>>>"+poNumber);
					
					}
					
					if (item.getFieldName().equalsIgnoreCase("uploadFile")) {
						
						byte[] theBytes = IOUtils.toByteArray(item.openStream());
						if(theBytes.length == 0){
							res.setContentType("text/plain");
							res.getWriter().println("Please Select An Attachment");
							return;
						} 
						
							String uniqueName = path +"/"+ poNumber + "/"+item.getName()+"/" ;
							FileObject fileObject = GaeVFS.resolveFile("gae://"	+ uniqueName);
							copyAndClose(theBytes, fileObject.getContent().getOutputStream());
							Attachment a = new Attachment();
							a.setUniqueName(uniqueName);
							a.setDescription(item.getName());
							a = new AttachmentDAO().insert(a);
							res.setContentType("text/plain");
							res.getWriter().println( a.getId()+":"+a.getUniqueName()+":"+a.getDescription()+":"+item.getName());
						
						
					}

				
			}
		} catch (Exception e) {
			throw new ServletException(e);
		} finally {
			GaeVFS.clearFilesCache();
		}

	}

	/**
	 * Copy the InputStream to the OutputStream then close them both.
	 */
	private static void copyAndClose(byte[] theBytes ,OutputStream out) throws IOException {
		InputStream bin = new ByteArrayInputStream(theBytes);
		IOUtils.copy(bin, out);
		out.flush();
		out.close();
		bin.close();

	}
	
	
}
